package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.annotation.SystemServiceLog;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.system.domain.*;
import org.footballmanager.pandafootball.system.domain.enums.FL;
import org.footballmanager.pandafootball.system.domain.enums.ZDZT;
import org.footballmanager.pandafootball.system.domain.enums.ZDZW;
import org.footballmanager.pandafootball.system.form.impl.FootSociatySearchForm;
import org.footballmanager.pandafootball.system.mapper.FootSociatyMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.List;

@Slf4j
@Service
public class FootSociatyServiceImpl extends ServiceImpl<FootSociaty> implements FootSociatyService {
    @Autowired
    private FootSociatyMapper footSociatyMapper;
    @Autowired
    private FootSociatyInfoService footSociatyInfoService;
    @Autowired
    private FootTeamService footTeamService;
    @Autowired
    private FootUserService footUserService;
    @Autowired
    private PhotoService photoService;
    @Autowired
    private ImageUpload imageUploader;
    @Autowired
    private FootLevelUpService footLevelUpService;

    /**
     * 创建战队
     *
     * @param userId  用户主键
     * @param entity  战队实体类
     * @param img     队标文件
     * @param request 请求
     * @return 是否成功
     */
    @Override
    @Transactional
    public boolean createSociaty(Long userId, FootSociaty entity, MultipartFile img, HttpServletRequest request) {
        //首先要确保没有战队
        FootSociaty fsold = this.findFootSociatyByName(entity.getName());
        Photo photo = new Photo();
        photo.setImg(entity.getImg());
        photo.setType(FL.WINGS);
        photoService.processPhoto(photo, img);
        photo.setUrl(imageUploader.addPhoto(img, request, FL.WINGS));
        photoService.save(photo, request);
        entity.setDanGradingId(1L);
        entity.setHaveNum(1);
        entity.setStatus(ZDZT.ENABLED);
        entity.setLevel(1);
        entity.setLiveness(0L);
        entity.setTotalNum(10);
        entity.setLogo(photo.getId());
        super.save(entity, request);
        FootUser user = footUserService.get(userId);
        if (null == fsold && null == this.findFootSociatyByUserId(userId) && user != null && user.getJoins()) {
            //花费100来创建战队
            FootTeam team = footTeamService.getTeamByUserid(userId);
            if (team != null && team.getQdZzj() > 50D) {
                team.setQdZzj(team.getQdZzj() - 50D);
                team.setYy(user.getNike() + "因创建战队花费" + 50D + "PB,当前球队的总资金为:" + team.getQdZzj() + "PB");
                footTeamService.updateNotNull(team, request);
            } else {
                return false;
            }
            FootSociatyInfo fsi = footSociatyInfoService.findFootSociatyInfoByUserid(userId, request);
            if (fsi != null) {
                fsi.setZdId(entity.getId());
                fsi.setHonor(100L);
                fsi.setRelation(ZDZW.CDR);
                fsi.setAgree(true);
                footSociatyInfoService.updateNotNull(fsi, request);
            } else {
                fsi = new FootSociatyInfo();
                fsi.setZdId(entity.getId());
                fsi.setUserId(userId);
                fsi.setRelation(ZDZW.CDR);
                fsi.setHonor(100L);
                fsi.setAgree(true);
                footSociatyInfoService.save(fsi, request);
            }
            return true;
        }
        return false;
    }

    /**
     * 解散战队
     *
     * @param userId  用户主键
     * @param request 请求
     */
    @Override
    public void deleteSociaty(Long userId, HttpServletRequest request) {
        FootSociaty fs = this.findFootSociatyByUserId(userId);
        if (null != fs) {
            List<FootSociatyInfo> users = footSociatyInfoService.findSociatyBySociatyId(fs.getId());
            if (null != users && !users.isEmpty()) {
                for (FootSociatyInfo fsi : users) {
                    fsi.setZdId(null);
                    fsi.setRelation(ZDZW.MEMBER);
                    fsi.setHonor(0L);
                    footSociatyInfoService.updateNotNull(fsi, request);
                }
            }
            this.delete(fs.getId(), request);
        }
    }

    /**
     * 根据用户主键找战队信息
     *
     * @param userId 用户主键
     * @return 战队信息
     */
    @Override
    public FootSociaty findFootSociatyByUserId(Long userId) {
        Example example = new Example(FootSociatyInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
        criteria.andEqualTo("delFlag", 0);
        FootSociatyInfo fsi = footSociatyInfoService.findByExample(example);
        if (fsi != null) {
            return this.get(fsi.getZdId());
        }
        return null;
    }

    /**
     * 根据名称查找战队信息
     *
     * @param name 战队名称
     * @return 战队信息
     */
    @Override
    public FootSociaty findFootSociatyByName(String name) {
        Example example = new Example(FootSociaty.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("name", name);
        criteria.andEqualTo("delFlag", 0);
        return this.findByExample(example);
    }

    /**
     * 是否可以加入战队
     *
     * @param userId  用户主键
     * @param zdId    战队主键
     * @param request 请求
     * @return 是否成功
     */
    @Override
    public void addSociaty(Long userId, Long zdId, HttpServletRequest request) {
        FootUser user = footUserService.get(userId);
        FootSociaty fs = this.get(zdId);
        FootSociaty fsy = this.findFootSociatyByUserId(userId);
        if (fsy != null) {
            return;
        }
        FootSociatyInfo fsi = footSociatyInfoService.findFootSociatyInfoByUserid(userId, request);
        boolean result = processSociatyError(zdId, fs, fsi, user);
        if (result) {
            fsi.setZdId(zdId);
            fsi.setAgree(false);
            footSociatyInfoService.updateNotNull(fsi, request);
        }
        request.getSession().setAttribute("mySociaty", fsi);
    }

    private boolean processSociatyError(Long zdId, FootSociaty fs, FootSociatyInfo fsi, FootUser user) {
        boolean flag1 = null == zdId || fs == null;
        boolean flag2 = fsi == null || user == null || !user.getJoins();
        return !flag1 && !flag2 && fs.getHaveNum() + 1 <= fs.getTotalNum();
    }

    /**
     * 退出战队
     *
     * @param userId  用户主键
     * @param zdId    战队主键
     * @param request 请求
     * @return 是否成功
     */
    @Override
    public boolean exitSociaty(Long userId, Long zdId, HttpServletRequest request) {
        if (null != zdId) {
            FootSociaty fs = this.get(zdId);
            if (fs != null && footSociatyInfoService.exitSociaty(userId, request)) {
                fs.setHaveNum(fs.getHaveNum() - 1);
                this.updateNotNull(fs, request);
                return true;
            }
        }
        return false;
    }

    @Override
    public void changeStatus(boolean status, HttpServletRequest request) {
        List<FootSociaty> list = this.getall();
        if (null != list && !list.isEmpty()) {
            for (FootSociaty fs : list) {
                if (status) {
                    fs.setStatus(ZDZT.ENABLED);
                } else {
                    fs.setStatus(ZDZT.CLOSE);
                }
                this.updateNotNull(fs, request);
            }
        }
    }

    @Override
    @Transactional
    @SystemServiceLog(description = "更新战队记录")
    public void update(FootSociaty entity, MultipartFile img, HttpServletRequest request) {
        FootSociaty oldEntity = this.get(entity.getId());
        if (oldEntity == null) {
            return;
        }
        if (oldEntity.getLogo() == null) {
            Photo photo = new Photo();
            photo.setImg(entity.getImg());
            photo.setType(FL.WINGS);
            photoService.processPhoto(photo, img);
            photo.setUrl(imageUploader.addPhoto(img, request, FL.WINGS));
            photoService.save(photo, request);
            oldEntity.setLogo(photo.getId());
        } else {
            Photo photo = photoService.get(oldEntity.getLogo());
            photo.setImg(entity.getImg());
            photo.setType(FL.WINGS);
            photoService.processPhoto(photo, img);
            photo.setUrl(imageUploader.upload(img, request, FL.WINGS));
            photoService.updateNotNull(photo, request);
            oldEntity.setLogo(photo.getId());
        }
        super.updateNotNull(oldEntity, request);
    }

    /**
     * 报分确认后更新数据
     *
     * @param bf      报分实体类
     * @param request 请求
     */
    @Override
    public void addEncourage(FootSociatyBfinfo bf, HttpServletRequest request) {
        FootSociaty zhufc = this.get(bf.getZd1());
        FootSociaty kefc = this.get(bf.getZd2());
        //战队排行数据更新
        if (zhufc != null && kefc != null) {
            if (bf.getJq1() > bf.getJq2()) {
                //2代表主队胜利,1代表平,0代表主队负
                zhufc.setJf(zhufc.getJf() + 3);
                zhufc.setWinTime(zhufc.getWinTime() + 1);
                kefc.setLoseTime(kefc.getLoseTime() + 1);
            } else if (bf.getJq1().equals(bf.getJq2())) {
                zhufc.setJf(zhufc.getJf() + 1);
                zhufc.setSameTime(zhufc.getSameTime() + 1);
                kefc.setJf(kefc.getJf() + 1);
                kefc.setSameTime(kefc.getSameTime() + 1);
            } else {
                zhufc.setLoseTime(zhufc.getLoseTime() + 1);
                kefc.setJf(kefc.getJf() + 3);
                kefc.setWinTime(kefc.getWinTime() + 1);
            }
        }
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
        this.reComputeRank(zhufc, kefc, request);
    }

    /**
     * 删除报分后更新数据
     *
     * @param bf      报分实体类
     * @param request 请求
     */
    @Override
    public void deleteEncourage(FootSociatyBfinfo bf, HttpServletRequest request) {
        FootSociaty zhufc = this.get(bf.getZd1());
        FootSociaty kefc = this.get(bf.getZd2());
        //战队排行数据更新
        if (zhufc != null && kefc != null) {
            if (bf.getJq1() > bf.getJq2()) {
                //2代表主队胜利,1代表平,0代表主队负
                zhufc.setJf(zhufc.getJf() - 3);
                zhufc.setWinTime(zhufc.getWinTime() - 1);
                kefc.setLoseTime(kefc.getLoseTime() - 1);
            } else if (bf.getJq1().equals(bf.getJq2())) {
                zhufc.setSameTime(zhufc.getSameTime() - 1);
                zhufc.setJf(zhufc.getJf() - 1);
                kefc.setJf(kefc.getJf() - 1);
                kefc.setSameTime(kefc.getSameTime() - 1);
            } else {
                zhufc.setLoseTime(zhufc.getLoseTime() - 1);
                kefc.setJf(kefc.getJf() - 3);
                kefc.setWinTime(kefc.getWinTime() - 1);
            }
        }
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
        this.reComputeRank(zhufc, kefc, request);
    }

    /**
     * 重新计算战队情况
     *
     * @param zhufc   主球队
     * @param kefc    客球队
     * @param request 请求
     */
    @Override
    public void reComputeRank(FootSociaty zhufc, FootSociaty kefc, HttpServletRequest request) {
        FootLevelUp zhuFootLevelUp = footLevelUpService.calculateLevel(zhufc, request);
        FootLevelUp keFootLevelUp = footLevelUpService.calculateLevel(kefc, request);
        zhufc.setLevel(zhuFootLevelUp.getLevel());
        zhufc.setLiveness(zhufc.getLiveness() + 50);
        zhufc.setDanGradingId(zhuFootLevelUp.getDanGradingId());
        kefc.setLevel(keFootLevelUp.getLevel());
        kefc.setLiveness(kefc.getLiveness() + 50);
        kefc.setDanGradingId(keFootLevelUp.getDanGradingId());
        this.updateNotNull(zhufc, request);
        this.updateNotNull(kefc, request);
    }

    /**
     * 查询
     *
     * @param footSociatySearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootSociaty> findall(FootSociatySearchForm footSociatySearchForm) {
        return footSociatyMapper.findall(footSociatySearchForm);
    }

    @Override
    public FootSociaty get(Serializable id) {
        return footSociatyMapper.findById(id);
    }

    /**
     * 查询
     *
     * @param entityname            实体类名
     * @param map                   参数
     * @param footSociatySearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootSociatySearchForm footSociatySearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footSociatySearchForm);
        Page<FootSociaty> page = PageHelper.startPage(footSociatySearchForm.getPageIndex(), footSociatySearchForm.getPageSize());
        List<FootSociaty> list = this.findall(footSociatySearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }

    /**
     * 删除所有
     *
     * @param footSociatySearchForm 条件
     * @param request               请求
     */
    @Override
    public void deleteAll(FootSociatySearchForm footSociatySearchForm, HttpServletRequest request) {
        if (footSociatySearchForm.getSelectIds() != null) {
            String[] result = footSociatySearchForm.getSelectIds().split(Constants.COMMA);
            for (String id : result) {
                this.delete(Long.parseLong(id), request);
            }
        }
    }

    /**
     * 获取战队TOP10
     *
     * @return 战队TOP10
     */
    @Override
    public List<FootSociaty> findZdTop10() {
        return footSociatyMapper.findall(new FootSociatySearchForm());
    }
}
